from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime, ForeignKey, JSON, Enum, Table
from sqlalchemy.orm import relationship
from datetime import datetime
from database import Base
import enum


class TaskPriorityEnum(str, enum.Enum):
    """任务优先级枚举"""
    URGENT = "urgent"
    NORMAL = "normal"


class TaskStatusEnum(str, enum.Enum):
    """任务状态枚举"""
    DRAFT = "draft"
    SCHEDULED = "scheduled"
    PENDING = "pending"
    IN_PROGRESS = "in_progress"
    PAUSED = "paused"
    COMPLETED = "completed"
    CANCELLED = "cancelled"
    FAILED = "failed"


class TaskExecuteTypeEnum(str, enum.Enum):
    """任务执行类型枚举"""
    IMMEDIATE = "immediate"
    SCHEDULED = "scheduled"
    MANUAL = "manual"


# 任务-航线关联表
# 支持多航线顺序执行，需要记录执行顺序
class TaskRoute(Base):
    __tablename__ = "task_routes"
    
    id = Column(Integer, primary_key=True, index=True)
    task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False)
    route_id = Column(Integer, ForeignKey('flight_routes.id'), nullable=False)
    order_index = Column(Integer, nullable=False, default=0)  # 执行顺序
    created_at = Column(DateTime, default=datetime.now)
    
    # 关系
    task = relationship("Task", back_populates="task_routes")
    route = relationship("FlightRoute")


class Task(Base):
    """任务表"""
    __tablename__ = "tasks"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(200), nullable=False, comment="任务名称")
    description = Column(Text, comment="任务描述")
    priority = Column(Enum(TaskPriorityEnum), default=TaskPriorityEnum.NORMAL, comment="优先级：紧急/普通")
    execute_type = Column(Enum(TaskExecuteTypeEnum), default=TaskExecuteTypeEnum.IMMEDIATE, comment="执行类型：立即执行/定时执行")
    scheduled_time = Column(DateTime, nullable=True, comment="计划执行时间")
    responsible_person_id = Column(Integer, ForeignKey('users.id'), comment="负责人ID")
    status = Column(Enum(TaskStatusEnum), default=TaskStatusEnum.DRAFT, comment="任务状态")
    
    # 关联配置
    detection_model_ids = Column(JSON, nullable=True, comment="绑定的检测模型ID列表")
    trigger_conditions = Column(JSON, nullable=True, comment="触发条件配置")
    
    # 异常策略
    exception_strategies = Column(JSON, nullable=True, comment="异常处理策略")
    
    # 航线坐标信息
    route_coordinates = Column(JSON, nullable=True, comment="航线坐标信息，从关联航线获取")
    
    # 任务执行信息
    start_time = Column(DateTime, nullable=True, comment="开始执行时间")
    end_time = Column(DateTime, nullable=True, comment="结束时间")
    progress = Column(Integer, default=0, comment="任务进度（百分比）")
    
    created_by = Column(Integer, ForeignKey('users.id'), comment="创建人ID")
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    
    # 关系
    负责人 = relationship("User", foreign_keys=[responsible_person_id], backref="responsible_tasks")
    created_user = relationship("User", foreign_keys=[created_by])
    task_routes = relationship("TaskRoute", back_populates="task", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<Task(id={self.id}, name='{self.name}', status='{self.status}')>"